package com.shop.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shop.dao.ProductDao;
import com.shop.entity.Product;
import com.shop.entity.ProductCategory;
@Repository
@Transactional
public class ProductDaoImpl extends HibernateTemplate implements ProductDao{
	
	@Autowired
	private SessionFactory sessionFactory; 
	
	@Override
	public List<Product> findAllProduct() {
		return (List<Product>)super.find("from Product");
	}

	@Override
	public Serializable addProduct(Product product) {
		return super.save(product);
	}

	@Override
	public Serializable deleteProduct(Product product) {
		super.delete(product);
		return null;
	}

	@Override
	public Serializable updateProduct(Product product) {
		super.update(product);
		return null;
	}

	@Override
	public Product selectProduct(Product product) {
		//根据商品的id 查询商品的信息
		String hql = "from Product where ep_id=?";
		Session session = sessionFactory.openSession();
		Query q = session.createQuery(hql);
		q.setInteger(0, product.getEpId());
		Product p = (Product)q.uniqueResult();
		return p;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Product> selectProductByType(ProductCategory productCategory) {
		String hql ="from Product where epc_id =?";
		System.out.println(sessionFactory);
		Session session = sessionFactory.openSession();
		Query q = session.createQuery(hql);
		System.out.println("前台传过来的类别id=="+productCategory.getEpcId());
		q.setInteger(0, productCategory.getEpcId());
		List<Product> plist = q.list();
		return plist;
	}

	@Override
	public int count(ProductCategory productCategory) {
		int count = selectProductByType(productCategory).size();
		System.out.println("根据类别查出的总记录数：="+count);
		return count;
	}
	

	@SuppressWarnings("deprecation")
	@Override
	public List<Product> selectProductByTypePage(ProductCategory productCategory,
			int pageindex, int pagesize) {
		String hql = "from Product where epc_id =?";
		
		System.out.println("前台传过来的类别id="+productCategory.getEpcId());
		
		Session session = sessionFactory.openSession();
		Query q = session.createQuery(hql);
		q.setInteger(0, productCategory.getEpcId());
		List<Product> plist = (List<Product>)q.setFirstResult((pageindex-1)*pagesize)
											.setMaxResults(pagesize).list();
		return plist;
	}
	
	
	
	

}
